<template>
  <div v-loading="loading" class="rich-wrap">
    <editor
      v-model="content"
      :init="editorConfig"
      same-site="None"
      :tinymce-script-src="tinymceScriptSrc"
      api-key="tvclo97rtdcd1pu647q57zg8fi1udi0h8ihr0jgqp68wn6qz"
      model-events="change"
    />
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
import { toStorage } from '@/utils'
export default {
  name: 'RichEditor',
  components: {
    Editor
  },
  props: {
    contents: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 500
    }
  },
  data() {
    return {
      loading: true,
      content: this.contents,
      dialog: false,
      baseUrl: process.env.VUE_APP_BASE_API + '/upload',
      tinyEditor: null,
      tinymceScriptSrc: '//cdn.allzhan.com/g/js/tinymce/tinymce.min.js',
      editorConfig: {
        branding: false,
        base_url: '//cdn.allzhan.com/g/js/tinymce',
        menubar: false,
        plugins: [
          'advlist autolink lists link charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount',
          'lineheight'
        ],
        toolbar: 'undo  redo | formatselect fontsizeselect lineheightselect ' +
          '| bold italic underline strikethrough | forecolor backcolor ' +
          '| alignleft aligncenter alignright alignfull | bullist numlist outdent indent | myButton table ' +
          '| removeformat',
        fontsize_formats: '11px 12px 14px 16px 18px 24px 36px 48px',
        toolbar_mode: 'Wrap',
        setup: editor => {
          let that = this;
          that.tinyEditor = editor;
          editor.ui.registry.addButton('myButton', {
            tooltip: 'Upload Image',
            icon: 'image',
            onAction() {
              document.getElementById('upload-file').click()
            }
          });
          editor.on('change', () => {
            this.$emit('changeContent', editor.getContent())
          });
          editor.on('init', () => {
            this.loading = false
          });
        },
        language: 'zh_CN'
      }
    };
  },
  computed: {
    style() {
      return this.active.options.style
    }
  },
  created() {
    this.editorConfig.height = this.height
  },
  methods: {
    beforeUpload (file) {
      if (!this.validImgUpload(file, this.maxSize)) {
        return false
      }
      return true
    },
    validImgUpload (file, size) {
      size = +size || 2048
      const isSizeOut = file.size / 1024 > size
      if (isSizeOut) {
        this.$message.error('上传图片大小不能超过' + toStorage(size * 1024))
      }
      return !isSizeOut
    },
    handleImageSuccess(res) {
      this.tinyEditor.insertContent(`<p><img src='${res.data.url}' /></p>`);
    }
  }
};
</script>

<style lang="scss">
  .rich-wrap {
    p:after {
      content: '';
      display: table;
      clear: both;
    }
  }
</style>


